<?php
defined('EXEC') or die();
$transacao = 'usuarios';
$modulo = Session::get('cd_modulo');

if(!$auth->isRead($transacao)){
	Util::info(Config::AUTH_MESSAGE);
	return true;
}

//Importando a classes
Loader::import('com.atitudeweb.SQL');

//Exclusão de vários ou um registro
if(isset($_POST['checkdel'])){
	if($auth->isDelete($transacao)){
		if(SQL::remove('tethys.tb_transacao', 'ci_transacao', $_POST['checkdel'])){
			Util::notice('Transação', 'Excluída com sucesso!');
		}
		else{
			Util::notice('Transação', 'Houve um erro ao excluir!', 'error');
		}
	}
	else{
		Util::info(Config::AUTH_MESSAGE);
	}
}

//Alteração ou inclusão de um registro
if(isset($_GET['db']) && isset($_GET['form'])){

	$ci_transacao = $_GET['form'];
	$nm_transacao = addslashes($_POST['nm_transacao']);
	$nm_label = addslashes($_POST['nm_label']);

	if($_GET['form'] == 0){ //cadastro
		$ciRow = query("select nextval('tethys.tb_transacao_ci_transacao_seq') as ci_transacao;")->fetch();
		$ci_transacao = $ciRow['ci_transacao'];
		$sql = "INSERT INTO tethys.tb_transacao(ci_transacao, nm_transacao, nm_label)
		VALUES ($ci_transacao, '$nm_transacao', '$nm_label');
		INSERT INTO tethys.tb_modulotransacao(cd_modulo, cd_transacao)
		VALUES ($modulo, $ci_transacao);";
	}
	elseif($_GET['form'] > 0){ //alteração
		$sql = "UPDATE tethys.tb_transacao
		   SET , nm_transacao='$nm_transacao', nm_label='$nm_label'
		 WHERE ci_transacao = $ci_transacao;
		DELETE FROM tethys.tb_modulotransacao
		 WHERE cd_modulo = $modulo and cd_transacao = $ci_transacao;
		INSERT INTO tethys.tb_modulotransacao(cd_modulo, cd_transacao)
		VALUES ($modulo, $ci_transacao);";
	}
	//echo $sql; die;
	if(execute($sql)){
		Controller::setInfo('Transações', 'Salvo com sucesso!');
		Controller::redirect(Util::setLink(array('form=null', 'db=null')));
	}
	else{
		Util::notice('Transações', 'Ocorreu um erro!', 'error');
	}
}

if(isset($_GET['form'])){ //Formulário para adição ou alteração de registro
	if($_GET['form'] == 0){
		if(!$auth->isCreate($transacao)){
			Util::info(Config::AUTH_MESSAGE);
			return true;
		}
	}
	else{
		if(!$auth->isUpdate($transacao)){
			Util::info(Config::AUTH_MESSAGE);
			return true;
		}
		$rowEdit = query("select * from tethys.tb_transacao where ci_transacao = ".$_GET['form'])->fetch();
	}
}
else{ //Consulta no banco para listagem dos registros
	$where = '';
	if(@$_POST['search1']){
		$term = addslashes($_POST['search1']);
		$where .= "and nm_transacao ilike '%{$term}%' ";
	}
	if(@$_POST['search2']){
		$term = addslashes($_POST['search2']);
		$where .= "and nm_label ilike '%{$term}%' ";
	}

	$sql = "select *
	from tethys.tb_transacao tt
	inner join tethys.tb_modulotransacao tmt on (tt.ci_transacao = tmt.cd_transacao)
	where tmt.cd_modulo = $modulo $where
	order by 2
	limit {$limitPagina} offset ".(($p - 1) * $limitPagina);
	$query = query($sql);
	$sqlNum = "select count(*) as num from tethys.tb_transacao tt
	inner join tethys.tb_modulotransacao tmt on (tt.ci_transacao = tmt.cd_transacao)
	where tmt.cd_modulo = $modulo $where";
	$rowNum = query($sqlNum)->fetch();
	$registros = $rowNum['num'];
	$paginacao = Util::pagination($registros, 4);
}
?>
<div id="container">

    <!-- NOME DO MÓDULO E FORMULÁRIO DE PESQUISA -->
    <table class="actiontable">
		<tr>
			<td width="40">
				<img src="assets/transacoes.png"/>
			</td>
			<td>
				<span class="actiontitle">Transações </span>
				<span class="actionview"> - <?php echo (!isset($_GET['form']) ? 'Pesquisa' : (@$_GET['form'] > 0 ? 'Edição' : 'Cadastro')); ?>
				</span>
			</td>
			<?php if(!isset($_GET['form'])){ ?>
				<td align="right">
					<button id="btAdd" class="btn btn-success btn-sm"><span class="glyphicon glyphicon-plus-sign"></span> Novo</button>
				</td>
			<?php } else{ ?>
				<td align="right">
					<button id="btVoltar" class="btn btn-success btn-sm" onclick="window.location='?page=acesso/transacao';"><span class="glyphicon glyphicon-chevron-left"></span> Voltar</button>
				</td>
			<?php } ?>
		</tr>
	</table>
    <?php if(!isset($_GET['form'])){ ?>
	<form action="<?php echo Util::setLink(array('p=null')); ?>" method="post" class="form-horizontal">
		<div class="form-group">
   			<label  class="control-label col-sm-2">Transação:</label>
   			<div class="col-sm-5">
   				<input type="text" name="search1" id="search1" value="<?php echo @$_POST['search1']; ?>" class="form-control input-sm col-xs-3" />
   			</div>
   		</div>
   		<div class="form-group">
   			<label  class="control-label col-sm-2">LABEL:</label>
   			<div class="col-sm-5">
   				<input type="text" name="search2" id="search2"  value="<?php echo @$_POST['search2']; ?>" class="form-control input-sm col-xs-3" />
   			</div>
   			<button id="btSearch" class="btn btn-success btn-sm"><span class="glyphicon glyphicon-search"></span> Consultar</button>
   		</div>
   	</form>
	<?php } ?>

	<?php if(!isset($_GET['form'])){ ?>

	<!-- LISTAGEM DOS REGISTROS -->
	<form method="post" id="formSearch">
	    <table class="table table-striped table-bordered table-hover">
	    	<thead>
	        	<tr class="ui-widget-header">
		        	<th width="25" class="check"><input type="checkbox" id="btCheckAll"/></th>
	                <th>ID</th>
					<th>Transação</th>
	                <th>LABEL</th>
	                <th></th>
	            </tr>
	    	</thead>
	        <tbody>
	        	<?php
	        	while($row = $query->fetch()){
	        		echo '<tr>
		            	<td class="check"><input type="checkbox" class="btCheck" name="checkdel[]" value="'.$row['ci_transacao'].'"/></td>
		                <td>'.$row['ci_transacao'].'</td>
						<td>'.$row['nm_transacao'].'</td>
		                <td>'.$row['nm_label'].'</td>
		                <td width="30" align="center">
		                	<div onclick="window.location=\''.Util::setLink(array('form='.$row['ci_transacao'], 'del=null')).'\';" class="btEdit ui-widget ui-helper-clearfix" title="Editar">
						    	<div class="btn btn-success btn-xs"><span class="glyphicon glyphicon-pencil"></span></div>
						    </div>
		                </td>
		        	</tr>';
				}
	        	?>
	        </tbody>
		</table>
	</form>
	<button id="btDel" class="btn btn-success btn-sm" title="Excluir selecionados"><span class="glyphicon glyphicon-trash"></span> Excluir</button>
	<?php echo $paginacao; ?>

    <?php } else{ ?>

	<!-- FORMULÁRIO DE CADASTRO -->
	<form action="<?php echo Util::setLink(array('db=1')) ?>" method="post" id="formInsertEdit" onsubmit="return test();">
   		<table border="0" style="margin: 0 auto;">
   			<tr><td></td><td><div class="validateTips">Preencha corretamente o formulário.</div></td></tr>
   			<tr>
   				<td align="right">Transação: *</td>
   				<td><input type="text" id="nm_transacao" name="nm_transacao" value="<?php echo trim(@$rowEdit['nm_transacao']); ?>" class="form-control input-sm" size="50" maxlength="50" /></td>
   			</tr>
   			<tr>
   				<td align="right">Label: *</td>
   				<td><input type="text" id="nm_label" name="nm_label" value="<?php echo trim(@$rowEdit['nm_label']); ?>" class="form-control input-sm" size="50"/></td>
   			</tr>
   			<tr>
   				<td></td>
   				<td><button id="btInsertEdit" class="btn btn-success btn-sm" type="submit"><span class="glyphicon glyphicon-floppy-disk"></span> 	Salvar</button></td>
   			</tr>
   		</table>
    </form>

	<?php } ?>

</div>
<div id="dialog_del" title="Aviso">
	<p>Tem certeza que deseja excluir os registros selecionados?</p>
</div>
<script type="text/javascript">
$(function(){
	$("#nm_transacao").keyup(function(){
		$(this).val($(this).val().toUpperCase());
	    var varString = $(this).val();
	    var stringAcentos = ('àâêôûãõáéíóúçüÀÂÊÔÛÃÕÁÉÍÓÚÇÜ');
	    var stringSemAcento = ('aaeouaoaeioucuAAEOUAOAEIOUCU');

	    var i = new Number();
	    var j = new Number();
	    var cString = new String();
	    var varRes = '';

	    for (i = 0; i < varString.length; i++) {
	        cString = varString.substring(i, i + 1);
	        for (j = 0; j < stringAcentos.length; j++) {
	            if (stringAcentos.substring(j, j + 1) == cString){
	                cString = stringSemAcento.substring(j, j + 1);
	            }
	        }
	        varRes += cString;
	    }
	    varRes = varRes.replace( /\s/g, '_');
	    $("#nm_label").val(varRes.toLowerCase());
	});
});
function test(){
	var valid = true;
	var nm_transacao = $("#nm_transacao").val();
	var nm_label = $("#nm_label").val();

	if (nm_transacao == '') {
		updateTips('O Campo Transacão está vázio');
		valid = false;
	}else if(nm_label == ''){
		updateTips('O Campo Label está vázio');
		valid = false;
	}else{
		$("#formInsertEdit").find("input").each(function(index){
			$(this).removeClass("ui-state-error");
		});

		valid = valid && checkLength('nm_transacao', 'Transação', 2);
		valid = valid && checkLength('nm_label', 'Label', 2);
	}
	return valid;
}
</script>